function data=bciReadDataTDT(bci,hdr,begSample,endSample)
% data=bciReadDataTDT(bci,hdr,begsample,endsample) %Reads a junk of data from the TDT buffer
%
% PURPOSE:
% Read a slice of data from the TDT databuffer. Note that the databuffer is
% implemented as a ring buffer. Thus, re-reading the same slice will
% produce different data after a while. 
%
% INPUT:
% bci:          A bci structure. Defines he blocks (tags e.g. Wav1) to read
%               in bci.TDT.blockNames2Read and the channels read from the block
%               in bci.TDT.channels2Read. Both are defined in bciGetParams
% hdr:          A hdr structure initialized and returned by bciReadRecorderHeader
% begsample:    The first sample to read from the data buffer
% endsample:    The last sample to read from the data buffer
%
% OUTPUT:
% data:         The data read from the buffer. Channels along the rows,
%               timepoints along the columns.
%
% TODO:
% Jochem: Check if this function correctly reads
% Jochem: delete unnecessary code fragments

% 101202 Jochem wrote it

%bci.TDT.channels2Read{1}=1:32; %TDT organizes channels in blocks. Channels are specified for each block separately.
%bci.TDT.blockNames2Read{1}='Wav1'; 


%nChansInWav=hdr.nChans/numWavs;

% if begsample>endsample %buffer wrapped around
%     datalength = hdr.BufferSize-begsample+endsample+1;
%     disp('overflow detected')
% else
%     datalength=(endsample-begsample+1);
% end


%The existence of the requested blocks (in TDTish Tag) and channels in the
%blocks has already been checked when hdr-structure was created. 
numWavs=length(bci.TDT.blockNames2Read);
dataLength=(endSample-begSample+1);
data = zeros(hdr.nChans,dataLength);
% We should wait a little
pause(1/hdr.Fs)

channelsAlreadyRead=0;
for k = 1:numWavs
    %We have to read all channels available in a block
    nChansInBlock=hdr.params.nChannels(bci.TDT.block2ReadIdx(k));
    bufferSize=bci.TDT.params.bufferSize(bci.TDT.block2ReadIdx(k));
    currentReadTarget=[hdr.dataBufferName '.' lower(hdr.params.dTagName{bci.TDT.block2ReadIdx(k)})];
    x=hdr.DA.ReadTargetVEX(currentReadTarget,...
        mod(begSample*nChansInBlock,bufferSize),dataLength*nChansInBlock,'F32','F64');
    % now we 
    x=reshape(x, hdr.params.nChannels(bci.TDT.block2ReadIdx(k)),(endSample-begSample+1)); %bci.TDT.block2ReadIdx(k) is the index of the currently requested block into the list of all available blocks 
    data(channelsAlreadyRead+bci.TDT.channels2Read{k},:)=x(bci.TDT.channels2Read{k},:); %select only requested channels
    %data((k-1)*nChansInWav+1:k*nChansInWav,:) = reshape(x, nChansInWav,(endsample-begsample+1));
    channelsAlreadyRead=channelsAlreadyRead+length(bci.TDT.channels2Read{k});
end
